package com.eduspace.eduplatform.wares.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.*;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * druid 配置.
 *
 * @author tbc on 2016/10/30 0:21.
 */
@Slf4j
@Configuration
@org.springframework.context.annotation.PropertySource(value = "classpath:jdbc.properties", encoding = "utf-8")
public class DruidConfiguration extends WebMvcConfigurerAdapter {

    @Value("${jdbc.druid.loginUsername:root}")
    private String loginUsername;
    @Value("${jdbc.druid.loginPassword:12345}")
    private String loginPassword;
    private static final String DB_PREFIX = "spring.datasource.";


    @Autowired
    private Environment environment;

    @Bean
    public DataSource druidDataSource() throws SQLException {
        Properties dbProperties = new Properties();
        Map<String, Object> map = new HashMap<>();
        for (PropertySource propertySource : ((AbstractEnvironment) environment).getPropertySources()) {
            getPropertiesFromSource(propertySource, map);
        }
        dbProperties.putAll(map);

        DruidDataSource dds = null;
        try {
            dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProperties);
            dds.init();
        } catch (Exception e) {
            throw new RuntimeException("load dataSource error, dbProperties is :" + dbProperties, e);
        }
        dds.setFilters("wall,stat");
        log.info("DruidDataSource created ...............");
        return dds;
    }

    private void getPropertiesFromSource(PropertySource<?> propertySource, Map<String, Object> map) {
        if (propertySource instanceof MapPropertySource) {
            for (String key : ((MapPropertySource) propertySource).getPropertyNames()) {
                if (key.startsWith(DB_PREFIX)) {
                    map.put(key.replaceFirst(DB_PREFIX, ""), propertySource.getProperty(key));
                } else if (key.startsWith(DB_PREFIX)) {
                    map.put(key.replaceFirst(DB_PREFIX, ""), propertySource.getProperty(key));
                }
            }
        }

        if (propertySource instanceof CompositePropertySource) {
            for (PropertySource<?> s : ((CompositePropertySource) propertySource)
                    .getPropertySources()) {
                getPropertiesFromSource(s, map);
            }
        }
    }

}
